package cur.tool.common.filter;

import cur.nature.framework.core.exception.BizException;
import cur.nature.framework.core.log.LOG;
import cur.nature.framework.mvc.http.ResponseObject;
import jakarta.validation.ConstraintViolationException;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class CustomControllerAdvice {
    @Order(0)
    @ExceptionHandler(value = BizException.class)
    public ResponseObject bizException(Throwable ex) {
        LOG.warn("业务处理异常:",ex);
        return ResponseObject.bizException(StringUtils.isEmpty(ex.getMessage())? "业务处理异常":ex.getMessage());
    }

    @Order(0)
    @ExceptionHandler(value = {ConstraintViolationException.class,MethodArgumentNotValidException.class})
    public ResponseObject constraintViolationException(Throwable ex) {
        LOG.warn("参数校验异常:" + ex.getMessage(),ex);
        StringBuilder stringBuilder = new StringBuilder();
        List<FieldError> bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
        for(FieldError fieldError: bindingResult){
            stringBuilder.append("字段( "+fieldError.getField()+" , "+fieldError.getRejectedValue()+" )校验失败:"+fieldError.getDefaultMessage()+" ; ");
        }
        String msg = stringBuilder.toString();
        return ResponseObject.bizException(msg);
    }

    @Order(1)
    @ExceptionHandler(value = {Throwable.class,Exception.class})
    public ResponseObject throwableException(Throwable ex) {
        LOG.warn("拦截Throwable。。。。。。。",ex);
        return ResponseObject.systemErr("系统异常,请联系管理员");
    }
}
